package com.apes.enquiry.compile;

import com.alibaba.fastjson.JSONObject;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.scm.masterdata.enumeration.model.Enumeration;
import com.apes.scm.masterdata.enumeration.repository.EnumerationRepository;
import com.apes.scm.masterdata.enumeration.repository.EnumerationTypeRepository;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

/**
 * 译码主入口
 * @author wuq
 * @Time 2023-6-11 16:00
 * @Description
 */
@Service
public class CompileCodeService {

    @Autowired
    private EnumerationTypeRepository enumerationTypeRepository;

    @Autowired
    private EnumerationRepository enumerationRepository;

    /** 编码平台类型枚举Code */
    public static final String COMPILE_PLATFORM_TYPE = "compilePlatformType";

    public String getCompilePlatform(){
        List<Enumeration> enumerations = enumerationRepository.findByTypeAndValid(COMPILE_PLATFORM_TYPE);
        if (CollectionUtils.isEmpty(enumerations)){
            throw new RuntimeException("系统未配置译码规则");
        }
        if (enumerations.size() > 1){
            throw new RuntimeException("系统配置多个译码规则,无法解析");
        }
        return enumerations.get(0).getCode();
    }

    /**
     * 根据车架号获取车型信息(执行顺序：1)
     *
     * @param request {"vinCode":"车架号"}
     */
    public JSONObject queryCarTypeByVin(SimpleRequest request){
        // todo 第一步：查询对应的规则或者策略，获取到指定译码平台
        String compilePlatform = getCompilePlatform();
        List<String> compilePlatformList = strategy(compilePlatform);

        // todo 第二步：根据第一步中的译码平台，获取车型信息
        JSONObject vinInfo = new JSONObject();
        for (int i = 0; i < compilePlatformList.size(); i++) {
            CompileCode compileCode = CompileCodeFactory.get(compilePlatformList.get(i));
            vinInfo = compileCode.queryCarTypeByVin(request);
            if (Objects.nonNull(vinInfo)){
                vinInfo.put("compilePlatform", compilePlatformList.get(i));
                return vinInfo;
            }
        }
        if (vinInfo.isEmpty()) throw new RuntimeException("您输入车牌号的VIN码有误，请核对后再输入~");
        return vinInfo;
    }

    /**
     * 根据 vin 码和配件别名查询配件标准名称(执行顺序：2)
     *
     * @param request {"vinCode":"车架号（选填）", "keyword":"配件别名（必填）", "compilePlatform":"译码平台（必填）"}
     */
    public JSONObject searchPartsHintsInfo(SimpleRequest request){
        // todo 第一步：拿到上一步（根据车架号获取车型信息）的规则或者策略，获取到指定译码平台
        JSONObject requestJO = request.getJO();
        String compilePlatform = requestJO.getString("compilePlatform");
        requestJO.remove("compilePlatform");
        request.setData(requestJO);

        // todo 第二步：根据第一步中的译码平台，获取配件标准名称
        CompileCode compileCode = CompileCodeFactory.get(compilePlatform);
        JSONObject result = compileCode.searchPartsHintsInfo(request);
        result.put("compilePlatform", compilePlatform);
        return result;
    }

    /**
     * 根据 vin+配件名称带出epc图片、OE号等信息(执行顺序：3)
     * @param request {"carTypeIds":[车型id集合]，"partsNames":["配件名称“], "vinAnalyseSource":车架号解析来源, "vinCode":"车架号", "compilePlatform":"译码平台（必填）"}
     * @return
     */
    public JSONObject queryPartsCodeInfo(SimpleRequest request){
        // todo 第一步：拿到第一步（根据车架号获取车型信息）的规则或者策略，获取到指定译码平台
        JSONObject requestJO = request.getJO();
        String compilePlatform = requestJO.getString("compilePlatform");
        requestJO.remove("compilePlatform");
        request.setData(requestJO);

        // todo 第二步：获取epc图片、OE号等信息
        CompileCode compileCode = CompileCodeFactory.get(compilePlatform);
        JSONObject result = compileCode.queryPartsCodeInfo(request);
        result.put("compilePlatform", compilePlatform);
        return result;
    }

    public void queryPartsReplaceCode(SimpleRequest request){
        // todo 第一步：查询对应的规则或者策略，获取到指定译码平台
        getCompilePlatform();
        CompileCode compileCode = CompileCodeFactory.get("");

    }

    /**
     * 根据策略确定执行顺序,把字符串转换成List集合
     * @param compilePlatform (列子：baturu/17vin)
     * @return [baturu, 17vin]
     */
    private List<String> strategy(String compilePlatform){
        List<String> compilePlatforms = new ArrayList<>();
        while (compilePlatform.contains("/")){
            compilePlatforms.add(compilePlatform.substring(0,compilePlatform.indexOf("/")));
            compilePlatform = compilePlatform.substring(compilePlatform.indexOf("/")+1);
            if (!compilePlatform.contains("/")){
                compilePlatforms.add(compilePlatform);
            }
        }
        if (compilePlatforms.isEmpty()){
            compilePlatforms.add(compilePlatform);
        }
        return compilePlatforms;
    }

    public JSONObject fullDecode(SimpleRequest request){
        JSONObject requestJO = request.getJO();
        /* 第一步：解析车型*/
        JSONObject carType = queryCarTypeByVin(request);
        requestJO.put("compilePlatform", carType.getString("compilePlatform"));
        request.setData(requestJO);

        /* 第二步：查询配件标准名称*/
        requestJO.put("partsNames", Arrays.asList(requestJO.getString("keyword")));
        requestJO.put("compilePlatform", carType.getString("compilePlatform"));
        if ("baturu".equals(carType.getString("compilePlatform"))){
            requestJO.put("carTypeIds", carType.getJSONObject("model").getJSONArray("carTypeIds"));
            requestJO.put("vinAnalyseSource", carType.getJSONObject("model").getIntValue("vinAnalyseSource"));
        }
        request.setData(requestJO);
        /* 第三步：译码配件详细信息*/
        return queryPartsCodeInfo(request);
    }

}
